//
//  IndexMenuUser.swift
//  browser
//
//  Created by Kotori on 2021/6/11.
//

import SwiftUI

struct IndexMenuUser: View {
    @State var isAddUser: Bool = false
    @State var currUsername = UserManager.currUsername
    var indexBtnDelegate: IndexBtnDelegate?
    var indexCallback: IndexCallback?
    
    var body: some View {
        Menu {
            
            Button(action: {}, label: {
                Text("当前用户：" + currUsername)
            })

            
            Divider()
            
            SwitchUserMenu(indexCallback: indexCallback, currUsername: $currUsername)
            
            Button("添加用户配置", action: {
                isAddUser = true
            })
        } label: {
            Image(systemName:"person.crop.circle").imageScale(.large)
        }
        .popover(isPresented: $isAddUser, content: {
            AddUserSetting()
        })
        
    }
}

struct SwitchUserMenu: View {
    var indexBtnDelegate: IndexBtnDelegate?
    var indexCallback: IndexCallback?
    @Binding var currUsername: String
    var userList: [String] = UserPreferenceManager.getAvailableUsers()
    var usernameList: [String] {
        userList.map({UserPreferenceManager.manager(of: UUID(uuidString: $0)).getUsername()})
    }
    
    var body: some View {
        Menu {
            ForEach(usernameList, id: \.self) { username in
                Button {
                    switchUser(to: userList[usernameList.firstIndex(of: username) ?? 0])
                } label: {
                    Text(username)
                }
            }
        } label: {
            Text("切换用户")
        }
    }
    
    func switchUser(to uuidString: String) {
        indexCallback?.changeCurrentUser(id: uuidString)
        currUsername = UserManager.currUsername
    }
}
struct IndexMenuUser_Previews: PreviewProvider {
    static var previews: some View {
        IndexMenuUser()
    }
}
